package com.net.shop.car.manager.ui.payment;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.net.shop.car.manager.App;
import com.net.shop.car.manager.R;
import com.net.shop.car.manager.api.model.ForPayGoods;
import com.net.shop.car.manager.api.model.Goods;
import com.net.shop.car.manager.api.model.PayType;
import com.net.shop.car.manager.api.volley.VolleyCenter;
import com.net.shop.car.manager.api.volley.VolleyListenerImpl;
import com.net.shop.car.manager.api.volley.request.PostDingDan;
import com.net.shop.car.manager.api.volley.response.dingdan.DingdanResponse;
import com.net.shop.car.manager.ui.FullScreenDialog;
import com.net.shop.car.manager.ui.view.MyListView;
import com.net.shop.car.manager.utils.StringUtils;
import com.net.shop.car.manager.utils.payment.PaymentUtils;
import com.net.shop.car.manager.utils.payment.Product;

public class PaymentDialog extends FullScreenDialog {
	private TextView titleView;
	private MyListView mGoodsListView;
	private MyListView mLvPaymenttypeList;
	private TextView mTvUserAllJf;
	private TextView totalTextView;
	private EditText mEtUserUseJf;
	private List<Goods> paymentGoods;
	private List<PayType> payTypes;
	
	private Button btnSure;
	
	private long userLeftVb;
	private long goodsAllJifen;
	private long jifenUsed;

	private BigDecimal totalMoney;

	private Map<Goods, Long> goodsUseJifenMap = new HashMap<Goods, Long>();
	private Map<PayType, Boolean> typeChecked = new HashMap<PayType, Boolean>();
	
	private NeedPayGoodsAdapter needPayGoodsAdapter;
	private PayTypeAdapter payTypeAdapter;

	public PaymentDialog(Context context) {
		super(context, R.style.Dialog_Fullscreen);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.dialog_payment);

		initViews();
	}

	public void setPaymentGoods(List<Goods> paymentGoods) {
		this.paymentGoods = paymentGoods;
		totalMoney = new BigDecimal(0);
		goodsAllJifen = 0;
		for (Goods goods : paymentGoods) {
			totalMoney = totalMoney.add(goods.getCheapPrice());
			if (goods.isSupportVB()) {
				goodsAllJifen += StringUtils.moneyToVB(goods.getCheapPrice());
			}
		}
	}
	
	public void setPayType(long vb,List<PayType> payTypes) {
		this.payTypes = payTypes;
		userLeftVb = vb;
		setTypeChecked(0);
	}
	
	/**
	 * @param type String
	 */
	private void setTypeChecked(int type) {
		for (PayType payType : payTypes) {
			if (type == payType.getDicName()) {
				typeChecked.put(payType, true);
			} else {
				typeChecked.put(payType, false);
			}
		}
	}

	/**
	 * 
	 */
	private void initViews() {
		// TODO Auto-generated method stub
		View view = findViewById(R.id.payment_title);
		view.findViewById(R.id.title_back_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});
		titleView = (TextView) view.findViewById(R.id.title_txt);
		titleView.setText("支付");

		mGoodsListView = (MyListView) findViewById(R.id.payment_good_list);

		totalTextView = (TextView) findViewById(R.id.payment_all_money);

		mLvPaymenttypeList = (MyListView) findViewById(R.id.payment_paytype_list);

		mTvUserAllJf = (TextView) findViewById(R.id.payment_user_all_jf);
		
		mEtUserUseJf = (EditText) findViewById(R.id.payment_user_use_jf);
		
		btnSure = (Button) findViewById(R.id.payment_btn_sure);
		btnSure.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				onSure();
			}
		});

		mTvUserAllJf.setText(userLeftVb + "");
		totalTextView.setText(totalMoney.toString() + "元");
		needPayGoodsAdapter = new NeedPayGoodsAdapter();
		mGoodsListView.setAdapter(needPayGoodsAdapter);
		
		setTextWatcher();

		payTypeAdapter = new PayTypeAdapter();
		mLvPaymenttypeList.setAdapter(payTypeAdapter);
		mLvPaymenttypeList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				PayType payType = payTypes.get(position);
				onTypeChecked(payType);
				payTypeAdapter.notifyDataSetChanged();
			}
		});
	}
	
	/**
	 * 
	 */
	private void onSure() {
		if(App.i().getUser() == null || App.i().needLogin) {
			activity.gotoLogin();
			return;
		}
		PayType type = null;
		for (PayType payType : typeChecked.keySet()) {
			if (typeChecked.get(payType)) {
				type = payType;
			}
		}
		if (type == null) {
			App.i().showToast("请选择支付方式");
			return;
		}
		final List<ForPayGoods> forPayGoodList = new ArrayList<ForPayGoods>();
		for (Goods good : paymentGoods) {
			ForPayGoods forPayGoods = new ForPayGoods(good);
			BigDecimal money = good.getCheapPrice();
			long jifen = goodsUseJifenMap.get(good) == null ? 0 : goodsUseJifenMap.get(good);
			forPayGoods.setUseVb(jifen);
			forPayGoods.setUseMoney(money.subtract(new BigDecimal(jifen /(float) 100)));
			forPayGoodList.add(forPayGoods);
		}
		activity.progressDialog.show();
		VolleyCenter.getVolley().addGetRequest(new PostDingDan(forPayGoodList, type.getDicName(),
				App.i().getUser().getMemberId()),
				new VolleyListenerImpl<DingdanResponse>(new DingdanResponse()) {

					@Override
					public void deleveryResponse(DingdanResponse response) {
						activity.progressDialog.dismiss();
						if (response.isSuccess()) {
							if (0 == response.getState()) {
								Product product = new Product();
								StringBuffer strBuffer = new StringBuffer();
								if(forPayGoodList.size() > 2) {
									strBuffer.append(forPayGoodList.get(0).getGoodName()+",");
									strBuffer.append(forPayGoodList.get(1).getGoodName()+"...");
								} else {
									for (int i = 0; i < forPayGoodList.size(); i++) {
										if(i ==  forPayGoodList.size() -1) {
											strBuffer.append(forPayGoodList.get(i).getGoodName());
										} else {
											strBuffer.append(forPayGoodList.get(i).getGoodName()+",");
										}
									}
								}
								
								product.setOrder(response.getOrderId());
								product.setSubject(strBuffer.toString());
								product.setPrice(response.getMoney().toString());
								PaymentUtils.getInstance().pay(product);
							} else {
								App.i().showToast("订单成功!");
								dismiss();
							}
						}
					}
		});
	}
	
	/**
	 * 
	 */
	private void setTextWatcher() {
		mEtUserUseJf.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				//计算输入完成后的钱数
				try {
					jifenUsed = Long.parseLong(s.toString());
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					jifenUsed = 0;
				}
				computeJifenUsed();
				needPayGoodsAdapter.notifyDataSetChanged();
			}
		});
		
		 InputFilter[] inputFilters = new InputFilter[1];
		 inputFilters[0] = new InputFilter() {
			
			@Override
			public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				if (source.toString().contains(".")) {
					return "";
				}
				String str = dest.toString();
				long value = 0;
				try {
					value = Long.parseLong(str + source);
				} catch (NumberFormatException e) {
					return "";
				}
				if (value > goodsAllJifen) {
					return "";
				}
				return source;
			}
		};
		
		mEtUserUseJf.setFilters(inputFilters);
	}
	
	private void computeJifenUsed() {
		long jifenUsedLeft = jifenUsed;
		goodsUseJifenMap.clear();
		for (Goods goods : paymentGoods) {
			if (jifenUsedLeft <= 0) {
				break;
			}
			if (goods.isSupportVB()) {
				long goodJifen = (long) (goods.getCheapPrice().doubleValue() * 100);
				if (goodJifen >= jifenUsedLeft) {
					goodsUseJifenMap.put(goods, jifenUsedLeft);
					break;
				} else {
					jifenUsedLeft = jifenUsedLeft-goodJifen;
					goodsUseJifenMap.put(goods, goodJifen);
				}
			}
		}
	}
	
	/**
	 * @param payType PayType
	 */
	private void onTypeChecked(PayType payType) {
		setTypeChecked(payType.getDicName());
		if(0 == payType.getDicName()) {
			mEtUserUseJf.setVisibility(View.GONE);
			mEtUserUseJf.setText("");
			jifenUsed = 0;
			computeJifenUsed();
			needPayGoodsAdapter.notifyDataSetChanged();
		} else {
			mEtUserUseJf.setVisibility(View.VISIBLE);
		}
		payTypeAdapter.notifyDataSetChanged();
	}

	private class NeedPayGoodsAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return paymentGoods == null ? 0 : paymentGoods.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub

			View currentView = convertView;
			if (currentView == null) {
				currentView = activity.inflater.inflate(
						R.layout.item_paymentgoods_list, parent, false);
				currentView.setTag(new PaymentHoldler(currentView));
			}
			PaymentHoldler holdler = (PaymentHoldler) currentView.getTag();
			holdler.setData(paymentGoods.get(position));
			return currentView;
		}
	}

	private class PaymentHoldler {
		private TextView mTvFuwuName;
		private TextView mTvFuwuPrice;
		private TextView mTvFuwuJifen;

		/**
		 * 
		 */
		public PaymentHoldler(View v) {
			mTvFuwuName = (TextView) v.findViewById(R.id.payment_listitem_name);
			mTvFuwuPrice = (TextView) v
					.findViewById(R.id.payment_listitem_money);
			mTvFuwuJifen = (TextView) v
					.findViewById(R.id.payment_listitem_jifen_use);
		}

		public void setData(Goods goods) {
			mTvFuwuName.setText(goods.getGoodName());
			mTvFuwuPrice.setText(goods.getCheapPrice().toString() + "元");

			Long goodsLong = goodsUseJifenMap.get(goods);
			if (goodsLong != null && goodsLong > 0) {
				StringBuffer stringBuffer = new StringBuffer("使用");
				stringBuffer.append(goodsLong + "积分,");
				stringBuffer.append("抵扣");
				stringBuffer.append(goodsLong /(float)100 + "元");
				mTvFuwuJifen.setText(stringBuffer.toString());
				mTvFuwuJifen.setVisibility(View.VISIBLE);
			} else {
				mTvFuwuJifen.setVisibility(View.GONE);
			}
		}
	}
	
	private class PayTypeAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return null == payTypes ? 0 : payTypes.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View currentView = convertView;
			if (currentView == null) {
				currentView = activity.inflater.inflate(R.layout.paytype_listitem, parent, false);
				currentView.setTag(new PayTypeViewHolder(currentView));
			}
			PayTypeViewHolder viewHolder = (PayTypeViewHolder) currentView.getTag();
			viewHolder.setData(payTypes.get(position));
			return currentView;
		}
	}
	
	private class PayTypeViewHolder {
		private TextView mName;
		private CheckBox mChek;
		private View view;

		/**
		 * 
		 */
		public PayTypeViewHolder(View v) {
			view = v;
			mName = (TextView) v.findViewById(R.id.paytype_name);
			mChek = (CheckBox) v
					.findViewById(R.id.paytype_check);
		}

		public void setData(final PayType type) {
			mName.setText(type.getDicValue());
			mChek.setChecked(typeChecked.get(type));
			view.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (mChek.isChecked()) {
						mChek.setChecked(false);
						typeChecked.put(type, false);
					} else {
						mChek.setChecked(true);
						typeChecked.put(type, true);
						onTypeChecked(type);
					}
				}
			});
		}
	}

}
